package cn.gson.crm.controller.teaching;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.crm.model.dao.ClassDao;
import cn.gson.crm.model.dao.ProjectDao;
import cn.gson.crm.model.dao.ProjectLeaderDao;
import cn.gson.crm.model.dao.ProjectMemberDao;
import cn.gson.crm.model.dao.StudentDao;
import cn.gson.crm.model.entity.Classes;
import cn.gson.crm.model.entity.Project;
import cn.gson.crm.model.entity.ProjectLeader;
import cn.gson.crm.model.entity.ProjectMembers;
import cn.gson.crm.model.entity.ProjectPlan;
import cn.gson.crm.model.entity.Student;
import cn.gson.crm.model.mapper.ClassesMapper;
import cn.gson.crm.model.mapper.ProjectMapper;
import lombok.extern.log4j.Log4j;

@Controller
@RequestMapping("/project")
@Log4j
public class ProjectController {
	@Autowired
	private ProjectMapper projectMapper;
	
	@Autowired
	private ProjectDao projectDao;
	
	@Autowired
	private StudentDao studentDao;
	
	@Autowired
	private ProjectLeaderDao leaderDao;
	
	@Autowired
	private ProjectMemberDao memberDao;
	
	@Autowired
	private ClassDao classDao;
	
	@Autowired
	private ClassesMapper claMapper;
	/**
	 * 项目列表
	 * @param project
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("list")
	@ResponseBody
	public Map<String,Object> index(Project project, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<Project> pageData=projectMapper.findAllProject(project);
		PageInfo<Project> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	/**
	 * 查询所有项目计划
	 * @param plan
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("plan")
	@ResponseBody
	public Map<String,Object> plan(ProjectPlan plan, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize,
			@RequestParam(name="title",required=false) String title,
			@RequestParam(name="buildTime",required=false) String buildTime,
			@RequestParam(name="classes",required=false) Classes classes){
		// 查询数据
		Map<String, Object> m = new HashMap<>();
		m.put("classes", classes);
		m.put("buildTime", buildTime);
		m.put("title", title);
		PageHelper.startPage(pageNum, pageSize);
		List<ProjectPlan> pageData=projectMapper.findAllPlan(m);
		System.out.println("pageData:"+pageData);
		PageInfo<ProjectPlan> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	/**
	 * 删除项目
	 * @param id
	 * @return
	 */
	@GetMapping("deleteproject/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> delete(@PathVariable("id") Long id) {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		Project p;
		if (id != null && (p = projectDao.findOne(id)) != null) {
			p.setDeleted(false);
			obj.put("success", true);
		} else {
			obj.put("message", "此项目不存在！");
		}
		return obj;
	}
	/**
	 * 删除组长
	 * @param id
	 * @return
	 */
	@GetMapping("deleteleader/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> deleteleader(@PathVariable("id") Long id) {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		ProjectLeader pl;
		if (id != null && (pl = leaderDao.findOne(id)) != null) {
			List<ProjectMembers> pm=memberDao.findByProjectLeaderId(pl.getId());
			for (ProjectMembers p : pm) {
				p.setDeleted(false);
				p.setStudent(null);
				p.setProjectLeader(null);
			}
			pl.setStudent(null);
			pl.setDeleted(false);
			obj.put("success", true);
		} else {
			obj.put("message", "此组长不存在！");
		}
		return obj;
	}
	/**
	 * 删除组员
	 * @param id
	 * @return
	 */
	@GetMapping("deleteMember/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> deleteMember(@PathVariable("id") Long id) {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		ProjectMembers pm;
		if (id != null && (pm = memberDao.findOne(id)) != null) {
			pm.setStudent(null);
			pm.setProjectLeader(null);
			pm.setDeleted(false);
			obj.put("success", true);
		} else {
			obj.put("message", "此组员不存在！");
		}
		return obj;
	}
	
	/**
	 * 打开添加项目界面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping({"/add_project","/add_project/{id}"})
	public String addproject(Classes cla,@PathVariable(name = "id", required = false)Long id, Model model) {
		if(id != null){
			Project project = projectDao.findOne(id);
				//如果是编辑，则将原有学生信息传回表单页面
				if(project!=null) {
					model.addAttribute("project", project);
				}
		}
		//查询班级
		List<Classes> cls =  claMapper.listClasses(cla);
		model.addAttribute("cls", cls);
		return "/project/add_project";
	}
	/**
	 * 添加项目
	 * @param student
	 * @param br
	 * @return
	 */
	@PostMapping("/save")
	@ResponseBody
	@Transactional
	public Map<String,Object> save(@Valid Project project,BindingResult br){
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		if(br.hasErrors()) {
			obj.put("message", "保存失败！");
			obj.put("erros", br.getFieldErrors());
		}else {
			if (project.getId() == null) {
				Long id=project.getClasses().getId();
				String title=project.getTitle();
				int count=projectMapper.countproject(id);
				int countTitle=projectMapper.countTitle(id, title);
				if(count>=1) {
					obj.put("message", "该班正在做项目哦，不能再发布项目！");
					return obj;
				}
				if(countTitle>1) {
					obj.put("message", "该班已做过该项目了哦！");
					return obj;
				}
			} else {
				//编辑的时的两种情况
				if (project.getTitle() != null ) {
					//有数据的时候，则表示更新数据
					project.setTitle(project.getTitle());
					project.setIntroduce(project.getIntroduce());
					project.setEntryTime(project.getEntryTime());
					project.setEndTime(project.getEndTime());
					project.setClasses(project.getClasses());
					project.setDeleted(true);
				} else {
					//没有数据，则查出原数据进行覆盖
					Project p = projectDao.findOne(project.getId());
					project.setTitle(p.getTitle());
					project.setIntroduce(p.getIntroduce());
					project.setEntryTime(p.getEntryTime());
					project.setEndTime(project.getEndTime());
					project.setClasses(p.getClasses());
					project.setDeleted(true);
				}
				Long id=project.getClasses().getId();
				String title=project.getTitle();
				int count=projectMapper.countproject(id);
				int countTitle=projectMapper.countTitle(id, title);
				if(countTitle>1) {
					obj.put("message", "该班已做过该项目了哦！");
					return obj;
				}else if(count>1) {
					obj.put("message", "该班正在做项目哦，不能再发布项目！");
					return obj;
				}
			}
				project.setStatus("开发中");
				project.setDeleted(true);
				projectDao.save(project);
				obj.put("success", true);
		}
		return obj;
	}
	/**
	 * 打开项目成员列表
	 * @param cla
	 * @param id
	 * @param model
	 * @return
	 */
	Long pid;
	@RequestMapping({"/project_members/{id}"})
	public String projectMember(Project pro,@PathVariable(name = "id", required = false)Long id, Model model) {
		if(id != null){
			pid=id;
			Project project = projectDao.findOne(pid);
				//如果是编辑，则将原有学生信息传回表单页面
				if(project!=null) {
					model.addAttribute("project", project);
					
				}
		}
		return "/project/project_members";
	}
	/**
	 * 项目组长列表
	 */
	@RequestMapping("listLeader")
	@ResponseBody
	public Map<String,Object> listMember(ProjectLeader leader, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<ProjectLeader> pageData=projectMapper.findAllLeader(pid);
		
		PageInfo<ProjectLeader> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	/**
	 * 打开添加组长界面
	 * @param cla
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping({"/add_leader","/add_leader/{id}"})
	public String addLeader(@PathVariable(name = "id", required = false)Long id, Model model) {
		if(id != null){
			ProjectLeader leader = leaderDao.findOne(id);
				//如果是编辑，则将原有信息传回表单页面
				if(leader!=null) {
					model.addAttribute("leader", leader);
				
				}
		}
		Project project = projectDao.findOne(pid);
		Long cid=project.getClasses().getId();
		model.addAttribute("project", project);
		
		//根据班级id查查学生id
		List<Long> studentid=projectMapper.findstudentId(cid,pid);
		//组长表中根据项目id查学生id
		List<Long> leaderid=projectMapper.findleader(pid);
		//组员表中根据组长id查学生id
		List<Long> sid=projectMapper.findmembersId(lid);
		//保存所有学生
		List<Student> students=new ArrayList<Student>();
		//保存项目学生组长id
		List<Student> stu=new ArrayList<Student>();
		//保存项目组员学生id
		List<Student> stu2=new ArrayList<Student>();
		studentid.removeAll(leaderid);
		studentid.removeAll(sid);
		
		for(int i=0;i<studentid.size();i++) {
			System.err.println(studentid);
			Long stuid=studentid.get(i);
			Student student=projectMapper.findAllstudent(stuid);
			
				students.add(student);
			}
				
		for(int i=0;i<leaderid.size();i++) {
			Long stuid=leaderid.get(i);
			Student student=projectMapper.findAllstudent(stuid);
			stu.add(student);
		}
		for(int i=0;i<sid.size();i++) {
			Long stuid=sid.get(i);
			Student student=projectMapper.findAllstudent(stuid);
			stu2.add(student);
		}
		model.addAttribute("student", students);
		return "/project/add_leader";
	}
	
	/**
	 * 保存添加组长数据
	 * @param leader
	 * @param br
	 * @return
	 */
	@PostMapping("/saveLeader")
	@ResponseBody
	@Transactional
	public Map<String,Object> saveLeader(@Valid ProjectLeader leader,BindingResult br){
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		if(br.hasErrors()) {
			obj.put("message", "保存失败！");
			obj.put("erros", br.getFieldErrors());
		}else {
				//编辑的时的两种情况
				if (leader.getStudent().getName() != null ) {
					//有数据的时候，则表示更新数据
					leader.setStudent(leader.getStudent());
					leader.setDeleted(true);
				} else {
					//没有数据，则查出原数据进行覆盖
					ProjectLeader pl = leaderDao.findOne(leader.getId());
					leader.setStudent(pl.getStudent());
					leader.setDeleted(true);
				}
				Long l=leader.getStudent().getId();
				Long p=leader.getProject().getId();
				int count=projectMapper.leaderCount(l,p);
				if(count>=1) {
					obj.put("message", "此人已是组长！");
					return obj;
				}
				Student stu=studentDao.findOne(l);
				stu.setLeader(true);
				leader.setDeleted(true);
				leader.getStudent().setLeader(true);
				leaderDao.save(leader);
				obj.put("success", true);
		}
		return obj;
	}
	/**
	 * 组员列表
	 * @param member
	 * @param id
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	Long lid;
	@RequestMapping("listMembers/{id}")
	@ResponseBody
	public Map<String,Object> listMembers(ProjectMembers member,@PathVariable(name = "id", required = false)Long id,  @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		lid=id;
		List<ProjectMembers> pageData=projectMapper.findAllMembers(lid);
		PageInfo<ProjectMembers> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	/**
	 * 打开分配组员界面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping({"add_member"})
	public String addMember( Model model) {
			ProjectLeader leader = leaderDao.findOne(lid);
				//如果是编辑，则将原有信息传回表单页面
				if(leader!=null) {
					model.addAttribute("leader", leader);
				}
		
		return "/project/add_member";
	}
	
	@RequestMapping("addMembers")
	@ResponseBody
	public Map<String,Object> addMembers(@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		//PageHelper.startPage(pageNum, pageSize);
		//根据班级id查查学生id
		Project project = projectDao.findOne(pid);
		Long cid=project.getClasses().getId();
		List<Long> studentid=projectMapper.findstudentId(cid,pid);
		//组长表中根据项目id查学生id
		List<Long> leaderid=projectMapper.findleader(pid);
		//组员表中根据组长id查学生id
		List<Long> sid=projectMapper.findmembersId(lid);
		//保存所有学生
		List<Student> students=new ArrayList<Student>();
		//保存项目学生组长id
		List<Student> stu=new ArrayList<Student>();
		//保存项目组员学生id
		List<Student> stu2=new ArrayList<Student>();
		studentid.removeAll(leaderid);
		studentid.removeAll(sid);
		for(int i=0;i<studentid.size();i++) {
			Long id=studentid.get(i);
			Student student=projectMapper.findAllstudent(id);
			
			students.add(student);
		}
		
		for(int i=0;i<leaderid.size();i++) {
			Long id=leaderid.get(i);
			Student student=projectMapper.findAllstudent(id);
			stu.add(student);
		}
		for(int i=0;i<sid.size();i++) {
			Long id=sid.get(i);
			Student student=projectMapper.findAllstudent(id);
			stu2.add(student);
		}
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", students.size());
		obj.put("rows", students);
		return obj;
	}
	
	@PostMapping("/savemembers/{names}")
	@ResponseBody
	@Transactional
	public Map<String,Object> savemembers(@Valid ProjectLeader leader,@PathVariable(name="names",required = false) Long[] stuId,BindingResult br){
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		if(br.hasErrors()) {
			obj.put("message", "保存失败！");
			obj.put("erros", br.getFieldErrors());
		}else {
			List<ProjectMembers> pm= new ArrayList<ProjectMembers>();
			List<Student> stu= new ArrayList<Student>();
			for(int i=0;i<stuId.length;i++) {
				ProjectMembers member = new ProjectMembers();
				Student	student=studentDao.findOne(stuId[i]);
				leader=leaderDao.findOne(lid);
				stu.add(student);
				member.setStudent(stu.get(i));
				member.setProjectLeader(leader);
				member.setDeleted(true);
				pm.add(member);
				
			}
			memberDao.save(pm);
			obj.put("success", true);
		}
		return obj;
	}
}